<template>
  <div class="app-container">
    <!-- 顶部筛选区域 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <div class="filter-content">
          <!-- 左侧筛选条件 -->
          <div class="filter-left">
            <div class="time-type-tabs">
              <el-button 
                :type="queryParams.timeType === 'day' ? 'primary' : ''" 
                @click="handleTimeTypeChange('day')"
                class="time-tab"
              >
                日
              </el-button>
              <el-button 
                :type="queryParams.timeType === 'month' ? 'primary' : ''" 
                @click="handleTimeTypeChange('month')"
                class="time-tab"
              >
                月
              </el-button>
              <el-button 
                :type="queryParams.timeType === 'year' ? 'primary' : ''" 
                @click="handleTimeTypeChange('year')"
                class="time-tab"
              >
                年
              </el-button>
            </div>
            <div class="date-picker">
              <el-date-picker
                v-model="queryParams.selectedDate"
                :type="getDatePickerType()"
                :format="getDateFormat()"
                :value-format="getDateFormat()"
                placeholder="选择日期"
                class="date-input"
              />
            </div>
            <div class="unit-type-select">
              <span class="select-label">用能单元类型</span>
              <el-select v-model="queryParams.unitType" class="select-input" placeholder="请选择">
                <el-option 
                  v-for="option in ENERGY_UNIT_TYPE_OPTIONS" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </div>
          </div>
          
          <!-- 右侧查询按钮 -->
          <div class="filter-right">
            <el-button type="primary" @click="handleQuery" :loading="loading" class="query-btn">
              查询
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-card class="table-card">
        <el-table
          :data="tableData"
          v-loading="loading"
          border
          style="width: 100%;"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266', textAlign: 'center' }"
        >
          <!-- 曲线选择列 -->
          <el-table-column label="曲线选择" width="100" align="center" fixed>
            <template #default="scope">
              <el-radio 
                v-model="selectedUnitId" 
                :label="scope.row.id"
                @change="handleUnitChange(scope.row)"
              >
                &nbsp;
              </el-radio>
            </template>
          </el-table-column>
          
          <!-- 用能单元名称列 -->
          <el-table-column prop="unitName" label="用能单元名称" min-width="200" align="center" fixed />
          
          <!-- 用电量列 -->
          <el-table-column label="用电量（kWh）" min-width="150" align="right">
            <template #default="scope">
              <span>{{ formatNumber(scope.row.consumption) }}</span>
            </template>
          </el-table-column>
          
          <!-- 电费列 -->
          <el-table-column label="电费（元）" min-width="150" align="right">
            <template #default="scope">
              <span>{{ formatNumber(scope.row.cost) }}</span>
            </template>
          </el-table-column>
          
          <!-- 时间列 -->
          <el-table-column prop="time" label="时间" min-width="150" align="center" />
          
          <!-- 总费用列 -->
          <el-table-column label="总费用（元）" min-width="150" align="right" fixed="right">
            <template #default="scope">
              <span class="total-cost">{{ formatNumber(scope.row.totalCost) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 左侧：总费电费图表 -->
      <div class="chart-container">
        <el-card class="chart-card">
          <div class="chart-header">
            <h3>总费电费（元）</h3>
          </div>
          <div class="chart-content">
            <v-chart class="chart" :option="costChartOption" :autoresize="true" />
          </div>
        </el-card>
      </div>

      <!-- 右侧：总费用电量图表 -->
      <div class="chart-container">
        <el-card class="chart-card">
          <div class="chart-header">
            <h3>总费用电量（kWh）</h3>
          </div>
          <div class="chart-content">
            <v-chart class="chart" :option="consumptionChartOption" :autoresize="true" />
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { getHourDeepStatCost } from '@/api/stat/home'
import { ElMessage } from 'element-plus'
import { ENERGY_UNIT_TYPE, ENERGY_UNIT_TYPE_OPTIONS } from '@/utils/enums'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
])

// 查询参数
const queryParams = reactive({
  timeType: 'day',
  selectedDate: '', // 初始为空，在onMounted中设置
  unitType: ENERGY_UNIT_TYPE.FACTORY, // 使用枚举值
  groupType: ENERGY_UNIT_TYPE.FACTORY // 使用枚举值
})

// 加载状态
const loading = ref(false)

// 选中的用能单元ID
const selectedUnitId = ref(null)

// 图表分组数据
const chartGroupedData = ref({})

// 表格数据
const tableData = ref([])

// 图表数据
const chartTimeLabels = ref([
  '0时', '1时', '2时', '3时', '4时', '5时', '6时', '7时', '8时', '9时', '10时', '11时',
  '12时', '13时', '14时', '15时', '16时', '17时', '18时', '19时', '20时', '21时', '22时', '23时'
])

const chartCostData = ref([
  500, 350, 420, 380, 450, 520, 680, 850, 920, 1100, 1280, 1420,
  1380, 1450, 1520, 1680, 1830, 1900, 1650, 1380, 950, 850, 650, 520
])

const chartConsumptionData = ref([
  720, 1150, 730, 920, 830, 720, 680, 920, 1230, 1020, 950, 1030,
  1150, 990, 1320, 870, 920, 1180, 1230, 1480, 1290, 1180, 1450, 1410
])

// 总费电费图表配置（折线图）
const costChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: chartTimeLabels.value,
    axisLabel: {
      color: '#606266'
    },
    axisLine: {
      lineStyle: {
        color: '#E4E7ED'
      }
    }
  },
  yAxis: {
    type: 'value',
    name: '元',
    nameTextStyle: {
      color: '#606266'
    },
    axisLabel: {
      color: '#606266',
      formatter: '{value}'
    },
    axisLine: {
      lineStyle: {
        color: '#E4E7ED'
      }
    },
    splitLine: {
      lineStyle: {
        color: '#E4E7ED',
        type: 'dashed'
      }
    }
  },
  series: [
    {
      name: '电费',
      type: 'line',
      smooth: true,
      data: chartCostData.value,
      lineStyle: {
        width: 2,
        color: '#409EFF'
      },
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(64, 158, 255, 0.3)'
            },
            {
              offset: 1,
              color: 'rgba(64, 158, 255, 0.05)'
            }
          ]
        }
      }
    }
  ]
}))

// 总费用电量图表配置（柱状图）
const consumptionChartOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: chartTimeLabels.value,
    axisLabel: {
      color: '#606266'
    },
    axisLine: {
      lineStyle: {
        color: '#E4E7ED'
      }
    }
  },
  yAxis: {
    type: 'value',
    name: 'kWh',
    nameTextStyle: {
      color: '#606266'
    },
    axisLabel: {
      color: '#606266',
      formatter: '{value}'
    },
    axisLine: {
      lineStyle: {
        color: '#E4E7ED'
      }
    },
    splitLine: {
      lineStyle: {
        color: '#E4E7ED',
        type: 'dashed'
      }
    }
  },
  series: [
    {
      name: '用电量',
      type: 'bar',
      data: chartConsumptionData.value,
      barWidth: '60%',
      itemStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: '#409EFF'
            },
            {
              offset: 1,
              color: '#66B1FF'
            }
          ]
        },
        borderRadius: [4, 4, 0, 0]
      },
      emphasis: {
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#66B1FF'
              },
              {
                offset: 1,
                color: '#409EFF'
              }
            ]
          }
        }
      }
    }
  ]
}))

// 获取日期选择器类型
const getDatePickerType = () => {
  const typeMap = {
    day: 'date',
    month: 'month',
    year: 'year'
  }
  return typeMap[queryParams.timeType] || 'date'
}

// 获取日期格式
const getDateFormat = () => {
  const formatMap = {
    day: 'YYYY-MM-DD',
    month: 'YYYY-MM',
    year: 'YYYY'
  }
  return formatMap[queryParams.timeType] || 'YYYY-MM-DD'
}

// 处理时间类型变化
const handleTimeTypeChange = (type) => {
  queryParams.timeType = type
  // 根据时间类型调整日期
  const now = new Date()
  if (type === 'day') {
    queryParams.selectedDate = formatDate(now, 'YYYY-MM-DD')
    chartTimeLabels.value = Array.from({ length: 24 }, (_, i) => `${i}时`)
  } else if (type === 'month') {
    queryParams.selectedDate = formatDate(now, 'YYYY-MM')
    const days = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate()
    chartTimeLabels.value = Array.from({ length: days }, (_, i) => `${i + 1}日`)
  } else if (type === 'year') {
    queryParams.selectedDate = formatDate(now, 'YYYY')
    chartTimeLabels.value = Array.from({ length: 12 }, (_, i) => `${i + 1}月`)
  }
  
  // 清空图表数据，避免显示假数据
  chartCostData.value = []
  chartConsumptionData.value = []
  chartGroupedData.value = {}
  selectedUnitId.value = null
  
  // 同步groupType - 使用枚举值
  queryParams.groupType = queryParams.unitType
  
  // 自动查询新数据
  handleQuery()
}

// 格式化日期
const formatDate = (date, format) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
}

// 格式化数字
const formatNumber = (value) => {
  if (value === null || value === undefined) return '-'
  return Number(value).toFixed(2)
}

// 处理接口返回的数据
const processApiData = (data) => {
  console.log('处理成本分析数据:', data)
  
  // 处理表格数据 - 使用totalStat
  if (data.totalStat && Array.isArray(data.totalStat) && data.totalStat.length > 0) {
    // 按groupId分组
    const groupedData = {}
    data.totalStat.forEach(item => {
      const groupId = item.group_id
      if (!groupedData[groupId]) {
        groupedData[groupId] = {
          id: groupId,
          unitName: item.groupName,
          time: item.hourName || queryParams.selectedDate,
          energyTypes: {}
        }
      }
      
      // 按能源类型累加
      const energyType = item.statisticsTypeName
      if (!groupedData[groupId].energyTypes[energyType]) {
        groupedData[groupId].energyTypes[energyType] = {
          sumValue: 0,
          costMoney: 0
        }
      }
      
      groupedData[groupId].energyTypes[energyType].sumValue += parseFloat(item.sum_value || 0)
      groupedData[groupId].energyTypes[energyType].costMoney += parseFloat(item.cost_money || 0)
    })
    
    // 转换为表格数据格式
    tableData.value = Object.values(groupedData).map(group => {
      const energyTypes = group.energyTypes
      const totalConsumption = Object.values(energyTypes).reduce((sum, type) => sum + type.sumValue, 0)
      const totalCost = Object.values(energyTypes).reduce((sum, type) => sum + type.costMoney, 0)
      
      return {
        id: group.id,
        unitName: group.unitName,
        consumption: parseFloat(totalConsumption.toFixed(2)),
        cost: parseFloat(totalCost.toFixed(2)),
        time: group.time,
        totalCost: parseFloat(totalCost.toFixed(2)),
        energyTypes: energyTypes // 保存详细数据供图表使用
      }
    })
    
    // 默认选中第一个
    if (tableData.value.length > 0) {
      selectedUnitId.value = tableData.value[0].id
    }
  } else {
    // 没有数据时清空表格
    tableData.value = []
    selectedUnitId.value = null
  }
  
  // 处理图表数据 - 使用stats
  if (data.stats && Array.isArray(data.stats) && data.stats.length > 0) {
    // 按groupId和energyType分组
    const groupedChartData = {}
    data.stats.forEach(item => {
      const groupId = item.group_id
      const energyType = item.statisticsTypeName
      
      if (!groupedChartData[groupId]) {
        groupedChartData[groupId] = {}
      }
      if (!groupedChartData[groupId][energyType]) {
        groupedChartData[groupId][energyType] = []
      }
      
      groupedChartData[groupId][energyType].push({
        timeLabel: item.hourName,
        sumValue: parseFloat((item.sum_value || 0).toFixed(2)),
        costMoney: parseFloat((item.cost_money || 0).toFixed(2))
      })
    })
    
    // 保存图表数据供后续使用
    chartGroupedData.value = groupedChartData
    
    // 如果有选中的用能单元，更新图表
    if (selectedUnitId.value && groupedChartData[selectedUnitId.value]) {
      updateChartsForSelectedUnit(selectedUnitId.value, groupedChartData[selectedUnitId.value])
    }
  } else {
    // 没有数据时清空图表数据
    chartGroupedData.value = {}
    chartTimeLabels.value = []
    chartCostData.value = []
    chartConsumptionData.value = []
  }
  
  console.log('处理后的表格数据:', tableData.value)
  console.log('处理后的图表分组数据:', chartGroupedData.value)
}

// 更新选中用能单元的图表数据
const updateChartsForSelectedUnit = (unitId, unitChartData) => {
  console.log('更新图表数据，用能单元ID:', unitId, '数据:', unitChartData)
  
  // 获取第一个能源类型的数据作为默认显示
  const energyTypes = Object.keys(unitChartData)
  if (energyTypes.length > 0) {
    const firstEnergyType = energyTypes[0]
    const chartData = unitChartData[firstEnergyType]
    
    // 更新图表时间标签和数据
    chartTimeLabels.value = chartData.map(item => item.timeLabel)
    chartCostData.value = chartData.map(item => item.costMoney)
    chartConsumptionData.value = chartData.map(item => item.sumValue)
    
    console.log('更新图表数据:', {
      timeLabels: chartTimeLabels.value,
      costData: chartCostData.value,
      consumptionData: chartConsumptionData.value
    })
  }
}

// 处理查询
const handleQuery = async () => {
  loading.value = true
  
  try {
    const params = {
      groupType: queryParams.groupType,
      statTime: queryParams.selectedDate
    }
    
    console.log('调用成本分析接口参数:', params)
    const response = await getHourDeepStatCost(params)
    console.log('接口返回数据:', response)
    
    if (response && response.code === 200 && response.data) {
      // 处理接口返回的数据
      processApiData(response.data)
    } else {
      ElMessage.warning('暂无数据')
    }
  } catch (error) {
    console.error('获取成本分析数据失败:', error)
    ElMessage.error('获取数据失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理用能单元选择变化
const handleUnitChange = (row) => {
  console.log('选中的用能单元:', row)
  
  // 更新图表数据
  if (chartGroupedData.value[row.id]) {
    updateChartsForSelectedUnit(row.id, chartGroupedData.value[row.id])
  }
}

// 监听unitType变化，同步groupType
watch(() => queryParams.unitType, (newValue) => {
  queryParams.groupType = newValue // 直接使用枚举值
})

// 初始化
onMounted(() => {
  // 设置默认日期为当天
  const now = new Date()
  queryParams.selectedDate = formatDate(now, 'YYYY-MM-DD')
  
  // 初始加载数据
  handleQuery()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #F1F2F5;
  min-height: 100vh;
}

// 筛选区域样式
.filter-section {
  margin-bottom: 20px;
  
  .filter-card {
    border-radius: 0;
    box-shadow: none;
    
    .filter-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      
      .filter-left {
        display: flex;
        align-items: center;
        gap: 12px;
        flex: 1;
        
        .time-type-tabs {
          display: flex;
          gap: 0;
          border: 1px solid #dcdfe6;
          border-radius: 6px;
          overflow: hidden;
          
          .time-tab {
            border: none;
            border-radius: 0;
            min-width: 50px;
            height: 32px;
            font-size: 14px;
            background: #ffffff;
            color: #606266;
            
            &:not(:last-child) {
              border-right: 1px solid #dcdfe6;
            }
            
            &.el-button--primary {
              background: #4fdaca;
              color: white;
              border-color: #4fdaca;
            }
            
            &:hover:not(.el-button--primary) {
              background: #f5f7fa;
            }
          }
        }
        
        .date-picker {
          .date-input {
            width: 160px;
            height: 32px;
          }
        }
        
        .unit-type-select {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .select-label {
            font-size: 14px;
            color: #606266;
            white-space: nowrap;
          }
          
          .select-input {
            width: 120px;
            height: 32px;
          }
        }
      }
      
      .filter-right {
        .query-btn {
          border-radius: 6px;
          height: 32px;
          background: #4fdaca;
          border-color: #4fdaca;
          
          &:hover {
            background: #32b7cb;
            border-color: #32b7cb;
          }
        }
      }
    }
  }
}

// 表格区域样式
.table-section {
  margin-bottom: 20px;
  
  .table-card {
    border-radius: 0;
    box-shadow: none;
  }
  
  .total-cost {
    color: #F56C6C;
    font-weight: 600;
  }
}

// 图表区域
.charts-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  
  .chart-container {
    .chart-card {
      border-radius: 0;
      box-shadow: none;
      height: 100%;
    }
    
    .chart-header {
      padding: 16px 20px 8px;
      
      h3 {
        font-size: 14px;
        font-weight: 500;
        color: #333;
        margin: 0;
      }
    }
    
    .chart-content {
      padding: 0 20px 20px;
      height: 400px;
      
      .chart {
        width: 100%;
        height: 100%;
      }
    }
  }
}

// Element Plus 组件样式覆盖
:deep(.el-card__body) {
  padding: 0;
}

:deep(.el-table) {
  border-radius: 0 !important;
  box-shadow: none !important;
  
  .el-table__header {
    background: transparent !important;
    
    tr {
      background: transparent !important;
    }
    
    th {
      background: #ffffff !important;
      color: #2c3e50;
      font-weight: 600;
      border-bottom: 1px solid #e4e7ed;
    }
  }
  
  .el-table__row {
    &:hover > td {
      background-color: #f5f7fa !important;
    }
  }
  
  td {
    background: #ffffff !important;
    border-bottom: 1px solid #f0f0f0;
  }
  
  // 固定列样式 - 确保有白色背景
  .el-table__fixed {
    background: #ffffff !important;
    
    .el-table__fixed-header-wrapper {
      th {
        background: #ffffff !important;
      }
    }
    
    .el-table__fixed-body-wrapper {
      td {
        background: #ffffff !important;
      }
      
      .el-table__row {
        &:hover > td {
          background-color: #f5f7fa !important;
        }
      }
    }
  }
  
  .el-radio {
    .el-radio__label {
      display: none;
    }
  }
}

:deep(.el-input) {
  .el-input__wrapper {
    border-radius: 6px;
    
    &:hover {
      border-color: #4fdaca;
    }
    
    &.is-focus {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

:deep(.el-date-editor) {
  .el-input__wrapper {
    border-radius: 6px;
    
    &:hover {
      border-color: #4fdaca;
    }
    
    &.is-focus {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

:deep(.el-button) {
  border-radius: 6px;
  
  &.el-button--primary {
    background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
    border-color: #4fdaca;
    
    &:hover {
      background: linear-gradient(135deg, #32b7cb 0%, #4fdaca 100%);
    }
  }
}

// 时间类型按钮组特殊样式
.time-type-tabs {
  :deep(.el-button) {
    border-radius: 0 !important;
    border: none !important;
    
    &.time-tab {
      background: #ffffff !important;
      color: #606266 !important;
      
      &.el-button--primary {
        background: #4fdaca !important;
        color: white !important;
      }
      
      &:hover:not(.el-button--primary) {
        background: #f5f7fa !important;
      }
      
      &:focus {
        outline: none;
        box-shadow: none;
      }
    }
  }
}

// 响应式布局
@media (max-width: 1400px) {
  .charts-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .filter-section {
    .filter-content {
      flex-direction: column;
      align-items: stretch;
      
      .filter-left {
        flex-direction: column;
        align-items: stretch;
      }
      
      .time-type-tabs,
      .date-picker,
      .unit-type-select {
        width: 100%;
      }
    }
  }
}
</style>
